#!/bin/bash
#sh ./all_merger_branch_name/get_merger_recods_after_date.sh --searchFromDateString "2022-12-26 10:45:24" --warningMergeBranchName "${warningMergeBranchName[*]}"
:<<!
获取指定日期之后的所有合入记录(已去除 HEAD -> 等)
!
#responseResult=$(git log --graph --pretty=format:'%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --after "10-12-2022" --merges )
#responseResult=$(git log --pretty=format:'%s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --after "10-12-2022" --merges)

#responseResult=$(git log --pretty=format:'%C(yellow)%H' --after "10-12-2022" --no-merges )

#git log --pretty=format:'-%C(yellow)%d%Creset %s' --after "2022-10-16"


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'


function debug_log() {
    if [ "${isRelease}" == true ]; then
        echo "$1"
    fi
}



# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute%/*} # 使用此方法可以避免路径上有..
# CommonFun_HomeDir_Absolute=${CurrentDIR_Script_Absolute}
#echo "CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute}"

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
get_merger_recods_after_date_script_path="$(sh ${qscript_path_get_filepath} qbase get_merger_recods_after_date)"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"



# shell 参数具名化                     
while [ -n "$1" ]
do
        case "$1" in
                -date|--searchFromDateString) searchFromDateString=$2; shift 2;;
                -exceptBranch|--exceptBranchNames) exceptBranchNames=$2; shift 2;;
                -warningMergeBranch|--warningMergeBranchName) warningMergeBranchName=$2; shift 2;;
                --) break ;;
                *) break ;;
        esac
done



exceptBranchNames=(${exceptBranchNames}) #记得外层加()转成数组
warningMergeBranchName=(${warningMergeBranchName}) #记得外层加()转成数组



:<<! 错误方法，有时候merger进来的信息不是形如"Merge branch 'dev_will_publish' into 'development'"标准格式，导致无法截取判断合入的分支名
echo "------下面开始获取本分支在${searchFromDateString}后提交的所有merges记录------"
#responseResult=$(git log --pretty=format:'%s' --after "2022-10-13" --merges)
responseResult=$(git log --pretty=format:'%s' --after "${searchFromDateString}" --merges)

echo "\n------从所有merges记录中提取所有merges的功能分支名------"
arr=(${responseResult})
num=${#arr[@]}
#echo "num=$num"
for ((i=0;i<num;i+=5))
{
    #imodel=$((i%5))
    mergeBranchName=${arr[i+2]}
    mergeBranchName=$(echo $mergeBranchName | sed "s/'//g")
    intoBranchName=${arr[i+4]}
    intoBranchName=$(echo $intoBranchName | sed "s/'//g")
    if [ ${intoBranchName} != "development" ]; then
        matchMergeBranchNames[${#matchMergeBranchNames[@]}]=${mergeBranchName}
    fi
}

matchMergeBranchNameCount=${#matchMergeBranchNames[@]}
if [ ${matchMergeBranchNameCount} == 0 ]; then
    echo "本分支在${searchFromDateString}后没有发现merges记录(第一条merger的不在此处处理)"
else
    echo "${matchMergeBranchNames[*]}"
fi
!





:<<! 正确方法，如下：
!
#echo "------下面开始获取本分支在${searchFromDateString}后包含的所有分支名------"
#[git log命令参数详解](http://news.558idc.com/288248.html)
debug_log "正在执行命令(获取本分支合入的分支(会含标签,记得去除)):《 sh ${get_merger_recods_after_date_script_path} -date \"${searchFromDateString}\" 》"
responseResult=$(sh ${get_merger_recods_after_date_script_path} -date "${searchFromDateString}")
debug_log "${GREEN}恭喜通过《 sh ${get_merger_recods_after_date_script_path} -date \"${searchFromDateString}\" 》，得到本分支合入的所有其他分支和标签为:\n>>>>>\n${BLUE}${responseResult}${GREEN}\n<<<<<<${NC}"
arr=(${responseResult})
num=${#arr[@]}
#echo "${arr[*]}"
#echo "num=$num"


for ((i=0;i<num;i+=1))
{
    mergeBranchName=${arr[i]}
    mergeBranchName=$(echo $mergeBranchName | sed "s/(//g" | sed "s/)//g" | sed "s/,//g") #去除左右括号
    mergeBranchName=${mergeBranchName##*/} # 取最后的component
    #echo "$((i+1)) mergeBranchName=${mergeBranchName}"
    if [ "${mergeBranchName}" == "tag:" ]; then
        #echo "$((i+1)) mergeBranchName=${mergeBranchName}=========跳过本身及其下一个"
        i=$((i+1));
        continue;
    fi
    
   if echo "${warningMergeBranchName[@]}" | grep -wq "${mergeBranchName}" &>/dev/null; then
        # echo "${PackageErrorMessage}"
        PackageErrorCode=1
        PackageErrorMessage="🍠友情警告提示：${mergeBranchName}:不应该是合进来才对(可能原因有些分支合入后，可能又从该分支开辟了新分支，但却没有在新分支上进行新的提交。导致打包分支找到该分支最后一条的提交有多个分支，针对这种情况请进行确认，并对确实没用的新分支进行删除或者进行新的提交)"
        
        echo '{"message":"'"$PackageErrorMessage"'","code":"'"${PackageErrorCode}"'"}'
        exit 1
    else
        #echo "${mergeBranchName}:ok"
        matchMergeBranchNames[${#matchMergeBranchNames[@]}]=${mergeBranchName}
    fi
}

#[shell 数组去重](https://www.jianshu.com/p/1043e40c0502)
matchMergeBranchNames=($(awk -v RS=' ' '!a[$1]++' <<< ${matchMergeBranchNames[@]}))


matchMergeBranchNameCount=${#matchMergeBranchNames[@]}
# if [ ${matchMergeBranchNameCount} == 0 ]; then
#     echo "${GREEN}恭喜:获得在 ${BLUE}${searchFromDateString} ${GREEN}后没含其他分支${NC}"
# else
#     echo "${GREEN}恭喜:获得在 ${BLUE}${searchFromDateString} ${GREEN}后合入的分支【可能】(因为有些分支合入后，可能又从该分支开辟了新分支，但没没有在新分支上提交。导致检查出该commit有多个分支，针对这种情况要在后面进行额外判断的忽略处理)有matchMergeBranchNames=${BLUE}${matchMergeBranchNames[*]}${NC}"
# fi

# 输出结果给外部
resultJsonString='{"message":"'"恭喜获取指定日期之后的所有合入记录(已去除 HEAD -> 等)成功"'","data":"'"${matchMergeBranchNames[*]}"'"}'
function is_valid_json() {
    echo "$1" | jq -e . >/dev/null 2>&1
    return $?
}

function is_invalid_json() {
    if is_valid_json "$1"; then
        return 1
    else
        return 0
    fi
}

if is_invalid_json "$resultJsonString"; then
    echo "${RED}您最后的结果${BLUE}${resultJsonString}${RED}不是标准json格式的字符串，请检查"
    exit 1
else
    echo "${resultJsonString}"
fi

# 取值示例
# matchMergeBranchNameJson=$(sh ${CurrentDIR_Script_Absolute}/get_merger_recods_after_date.sh --searchFromDateString "${searchFromDateString}" --currentBranch "${currentBranch}" --warningMergeBranchName "${warningMergeBranchName[*]}")
# matchMergeBranchNames=$(echo "$matchMergeBranchNameJson" | jq -r '.data')



